﻿using Dapper;
using Dapper_Core.Basic;
using Dapper_Core.DAL.Interface;
using Dapper_Core.Table;
using System;
using System.Collections.Generic;
using System.Text;

namespace Dapper_Core.DAL.Impl
{
    /// <summary>
    /// 同步引用属性的抽象类
    /// </summary>
    public class AbstractSyncReference : ISyncReference
    {
        public virtual void SyncReferenceProperty(BaseModel model)
        {
            
        }

        /// <summary>
        /// 为列表中的每个DTO同步引用属性
        /// </summary>
        /// <param name="modelList"></param>
        /// <param name="idFieldNameString">外键在本表的属性名</param>
        /// <param name="propertyNameString">外键对象对应的属性名</param>
        public virtual void SyncReferenceProperty<T>(IEnumerable<BaseModel> modelList,
            string idFieldNameString,
            string propertyNameString)
            where T : BaseModel, new()
        {
            SyncReferenceProperty<T>(modelList, new KeyValuePair<string, string>(idFieldNameString, "Id"), propertyNameString);
        }

        /// <summary>
        /// 为列表中的每个DTO同步引用属性
        /// </summary>
        /// <param name="modelList"></param>
        /// <param name="pair">Key是外键在本表的属性名、Value是外键在原表对应的属性名</param>
        /// <param name="propertyNameString">外键对象在本表对应的属性名</param>
        public virtual void SyncReferenceProperty<T>(IEnumerable<BaseModel> modelList,
            KeyValuePair<string, string> pair,
            string propertyNameString)
            where T : BaseModel, new()
        {
            if (!modelList.HasData()) return;
            object value = null;
            BaseRepository <T> baseRepository = new BaseRepository<T> ();
            foreach (var model in modelList)
            {
                value = model.GetFieldValue(pair.Key);
                if (value.IsEmpty()) continue;
                string where = "where 1=1";
                DynamicParameters parameters = new DynamicParameters();
                where += $" and {pair.Value}=@{pair.Value}";
                parameters.Add(pair.Value, value);
                T property = baseRepository.GetFirst(where, parameters);
                model.SetFieldValue(propertyNameString, property);
            }
        }
    }
}
